package com.mt.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.config.FilmCacheManager;
import com.mt.mapper.FilmMapper;
import com.mt.RedisUtils;
import com.mt.enums.FilmListType;
import com.mt.enums.Status;
import com.mt.exception.GlobalException;
import com.mt.pojo.Film;
import com.mt.pojo.FilmComment;
import com.mt.pojo.FilmTag;
import com.mt.service.ExpectNumService;
import com.mt.service.FilmCommentService;
import com.mt.service.FilmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.mt.constants.SYS.TOP_FILM_CACHE;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2020-11-12
 */
@Service
@Slf4j
public class FilmServiceImpl extends ServiceImpl<FilmMapper, Film> implements FilmService {
    @Autowired
    RedisUtils redisUtils;

    @Resource
    FilmMapper filmMapper;

    @Resource
    ExpectNumService expectNumService;

    @Resource
    FilmCommentService commentService;

    /**
     * 获取上映的电影列表
     */
    @Override
    public List<Film> listFilms(int currentPage, int pageSize) {
        IPage<Film> page = new Page<>(currentPage, pageSize);
        String date = DateUtil.date().toString("yyyy-MM-dd");
        List<Film> films = filmMapper.listAll(page, date);
        return films;
    }

    /**
     * 获取所有电影分页列表
     */
    @Override
    public IPage<Film> pageFilms(int currentPage, int pageSize,String filmName) {
        IPage<Film> page = new Page<>(currentPage, pageSize);
        if (StrUtil.isNotBlank(filmName)) {
            filmName = "%"+filmName+"%";
        }else {
            filmName =null;
        }
        List<Film> films = filmMapper.pageFilms(page,filmName);
        page.setRecords(films);
        return page;
    }

    @Override
    public List<Film> getAllFilms() {
        String date = DateUtil.date().toString("yyyy-MM-dd");
        List<Film> films = filmMapper.getFilms(date);
        return films;
    }

    @Override
    public List<Film> listRecentlyReleaseFilms() {
        //查询当天日期
        String date = DateUtil.date().toString("yyyy-MM-dd");
        List<Film> films = filmMapper.listRecentlyReleaseFilms(date);
        return films;
    }

    /**
     * 分页筛选电影
     *
     * @param tagIds      电影标签
     * @param releaseYear 上映年份
     */
    @Override
    public List<Film> searchFilm(int currentPage, int pageSize, List<Integer> tagIds, String releaseYear) {
        if ((tagIds == null || tagIds.size() == 0) && StrUtil.isBlank(releaseYear)) {
            return listFilms(currentPage, pageSize);
        }
        if (releaseYear.length() != 4) {
            throw new GlobalException(Status.PARAM_ERROR);
        }
        String start = DateUtil.parse(releaseYear + "-1-1").toString();
        String end = DateUtil.endOfYear(DateUtil.parse(start)).toString();
        IPage<Film> page = new Page<>(currentPage, pageSize);
        List<Film> films = filmMapper.searchFilmList(page, tagIds, start, end);

        return films;
    }

    @Override
    public List<Film> searchFilm(String filmName) {
        return filmMapper.searchFilm("%" + filmName + "%");
    }


    /**
     * 电影详情信息
     */
    @Override
    public Film getFilmDetail(Integer filmId, String userId) {
        log.info("进入filmService : 参数" + filmId + "," + userId);
        Film film = filmMapper.getFilmDetail(filmId);
        if (film == null) {
            throw new GlobalException(Status.FILM_INFO_ERROR);
        }
        if (StrUtil.isBlank(userId)) {
            return film;
        }
        Page<FilmComment> page = new Page<>(1, 10);
        //todo 需要修改为调用service中的逻辑操作 需要查询上查询的评论点赞状态
        List<FilmComment> commentList = commentService.pageCommentByFilmId(1,
                10, userId, filmId, FilmListType.HOT);
        film.setComments(commentList);
        int expectStatus = expectNumService.getExpectStatus(userId, filmId);
        film.setIsExpect(expectStatus);
        //调用点赞状态方法(需要新增传入用户参数)
        return film;
    }

    @Override
    public List<FilmTag> getTags() {
        return filmMapper.getAllTags();
    }


    @Override
    public List<Film> getFilmsById(List<Integer> ids) {
        System.out.println(ids);
        String date = DateUtil.date().toString("yyyy-MM-dd");
        List<Film> films = filmMapper.getFilmsById(ids, date);
        System.out.println(films);
        if (films == null){
            films = new ArrayList<>();
        }
        return films;
    }

    /**
     * 上映电影信息
     */
    @Override
    public boolean addFilm(Film film) {
        if (StrUtil.isBlank(film.getFilmName())) {
            throw new GlobalException(Status.PARAM_ERROR, "电影名不可以为空");
        }
        filmMapper.insert(film);
        if (film.getType() != 0){
            filmMapper.distributeTag2Film(film.getId(),film.getType());
        }else {
            throw  new GlobalException(Status.PARAM_ERROR);
        }

        return true;
    }

    /**
     * 修改电影信息
     */
    @Override
    public boolean modifyFilm(Film film) {
        if (filmMapper.selectById(film.getId()) == null) {
            throw new GlobalException(Status.NOT_EXIST_FILM);
        }
        // film.setUpdateTime(DateUtil.parse(DateUtil.now()));
        int update = filmMapper.updateById(film);
        //System.out.println(film.getType());
        filmMapper.modifyTag2Film(film.getId(),film.getType());

      /*  if (update>0 && film.getType()!=0){

        }else {
            throw new GlobalException(Status.ERROR);
        }*/
        return true;
    }

    /**
     * 获取top榜单推荐电影
     * 使用缓存优化
     */
    @Override
    public List<Film> getTopFilm() {
        List<Film> topList = CollUtil.newArrayList();
        if (redisUtils.exists(TOP_FILM_CACHE)) {
            String cache = (String) redisUtils.get(TOP_FILM_CACHE);
            topList = JSONUtil.toBean(cache, List.class);
        } else if (FilmCacheManager.getInstance().containsKey(TOP_FILM_CACHE)) {
            topList = FilmCacheManager.getInstance().get(TOP_FILM_CACHE);
        }

        if (topList.isEmpty()) {
            IPage<Film> page = new Page<>(1, 50);
            topList = filmMapper.listHotFilm(page);
        }
        return topList;
    }


   /* public boolean countWatchedTotalNum(){
        Map<String, Object> hashKeys = redisUtils.getHashKeys(WATCHED_NUM_KEY);
        List<WatchedNumVO> numList = CollUtil.newArrayList();
        Map<Integer, Integer> numMap = CollUtil.newHashMap();
        hashKeys.keySet().forEach(key -> {
            String[] split = key.split("::");
            int filmId = Integer.parseInt(split[0]);
            String userId = split[1];
            int status = (Integer) hashKeys.get(key);

            WatchedNumVO watchedNumVO = new WatchedNumVO(filmId,userId,status);
            //统计数量
            if (status == 1) {
                if (numMap.containsKey(filmId)) {
                    Integer num = numMap.get(filmId);
                    //点赞
                    numMap.replace(filmId, num + 1);
                } else {
                    numMap.put(filmId, 1);
                }
            }else {
                if (numMap.containsKey(filmId)) {
                    Integer num = numMap.get(filmId);
                    //点赞
                    numMap.replace(filmId, num - 1);
                }else {
                    numMap.put(filmId, -1);
                }
            }
            numList.add(watchedNumVO);
        });
    }*/


}
